package com.chalk.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.chalk.common.util.Result;
import com.chalk.config.base.BaseController;
import com.chalk.model.TaskJob;
import com.chalk.service.TaskJobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.Set;

/**
 * 系统定时任务表(TaskJob)表控制层
 *
 * @author maxiaoqiang
 * @since 2019-03-28 09:54:29
 */
@Api(value = "系统定时任务表接口", tags = "系统定时任务表模块")
@RestController
@RequestMapping("/v1/taskJob")
public class TaskJobController extends BaseController {

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    @Autowired
    private TaskJobService taskJobService;

    /**
     * 系统定时任务表列表
     *
     * @param current 当前页数
     * @param size    每页显示条数
     * @param taskJob 查询实体
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "查询系统定时任务表列表", notes = "查询系统定时任务表列表", response = Result.class)
    @GetMapping
    public Result selectAll(Integer current, Integer size, TaskJob taskJob) {
        return Result.success(this.taskJobService.selectPage(this.getPage(current, size), new EntityWrapper<TaskJob>(taskJob)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "查询系统定时任务表", notes = "查询系统定时任务表", response = Result.class)
    @GetMapping("{id}")
    public Result selectOne(
            @ApiParam(name = "id", value = "主键", required = true, example = "1")
            @PathVariable String id) {
        return Result.success(this.taskJobService.selectById(id));
    }


    /**
     * 保存系统定时任务表
     *
     * @param taskJob 实体对象
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "保存taskJob", notes = "保存taskJob", response = Result.class)
    @PostMapping
    public Result insert(
            @ApiParam(name = "taskJob", value = "传入json格式", required = true)
            @RequestBody TaskJob taskJob) {
        DateTime date = DateUtil.date();
        taskJob.setCreateTime(date);
        taskJob.setUpdateTime(date);
        return Result.success(this.taskJobService.insert(taskJob));
    }

    /**
     * 修改系统定时任务表
     *
     * @param taskJob 实体对象
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "修改系统定时任务表", notes = "修改系统定时任务表", response = Result.class)
    @PutMapping
    public Result update(
            @ApiParam(name = "taskJob", value = "传入json格式", required = true)
            @RequestBody TaskJob taskJob) {
        taskJob.setUpdateTime(DateUtil.date());
        return Result.success(this.taskJobService.updateById(taskJob));
    }

    /**
     * 逻辑删除系统定时任务表
     *
     * @param ids 主键集合
     * @return Result 返回统一结果model
     */
    @ApiOperation(value = "批量删除系统定时任务表", notes = "批量删除系统定时任务表", response = Result.class)
    @DeleteMapping
    public Result delete(
            @ApiParam(name = "ids", value = "传数组", required = true)
            @RequestBody String[] ids) {
        return Result.success(this.taskJobService.deleteBatchByPrimaryKey(ids));
    }

    private Page<TaskJob> getPage(Integer current, Integer size) {
        Page<TaskJob> page = new Page<>();
        if (current != null) {
            page.setCurrent(current);
        }
        if (size != null) {
            page.setSize(size);
        }
        return page;
    }

    /**
     * 重新启动所有的job
     */
    @ApiOperation(value = "启动所有任务", notes = "启动所有任务", response = Result.class)
    @GetMapping("/startJob")
    private void reStartAllJobs() throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        Set<JobKey> set = scheduler.getJobKeys(GroupMatcher.anyGroup());
        for (JobKey jobKey : set) {
            scheduler.deleteJob(jobKey);
        }
        for (TaskJob job : taskJobService.selectList(new EntityWrapper<TaskJob>())) {
            logger.info("Job register name : {} , group : {} , cron : {}", job.getJobName(), job.getJobClassName(), job.getTimerRule());
            JobDataMap map = taskJobService.getJobDataMap(job);
            JobKey jobKey = taskJobService.getJobKey(job);
            JobDetail jobDetail = taskJobService.geJobDetail(jobKey, job.getJobDescription(), map);
            if (0 == job.getIsAvailable()) {
                scheduler.scheduleJob(jobDetail, taskJobService.getTrigger(job));
            } else {
                logger.info("Job jump name : {} , Because {} status is {}", job.getJobName(), job.getJobName(), job.getIsAvailable());
            }

        }
    }


    /**
     * 初始化启动所有的Job
     */
    @PostConstruct
    public void initialize() {
        /*try {
            reStartAllJobs();
            logger.info("INIT SUCCESS");
        } catch (SchedulerException e) {
            logger.info("INIT EXCEPTION : " + e.getMessage());
            e.printStackTrace();
        }*/
    }
}